<template>
  <div class="purchase-demand-container">
    <!-- 顶部栏：左侧新建，右侧关键词+状态+按钮（样式对齐第一张图） -->
    <div class="topbar">
      <div class="left">
        <el-button type="primary" @click="openAdd">新建</el-button>
      </div>
      <div class="right">
        <span class="label">关键词</span>
        <el-input v-model="query.keyword" placeholder="请输入关键词" class="kw-input" clearable />
        <span class="label">状态</span>
        <el-select v-model="query.purchaseStatus" class="status-select" placeholder="全部" clearable>
          <el-option :value="''" label="全部" />
          <el-option :value="0" label="待采购入库" />
          <el-option :value="1" label="部分采购入库" />
          <el-option :value="2" label="全部采购入库" />
        </el-select>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </div>
    </div>

    <!-- 占位：列表区域由现有页面实现，这里仅调整顶部栏样式 -->
    <!-- 列表区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th>采购需求单号</th>
            <th>采购状态</th>
            <th>生产计划</th>
            <th>生产产品</th>
            <th>所需物料</th>
            <th>分类</th>
            <th>规格</th>
            <th>单位</th>
            <th>可用库存</th>
            <th>所需用量</th>
            <th>净需求</th>
            <th>待采购数量</th>
            <th>已采购入库数量</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading"><td colspan="13" style="text-align:center;padding:20px;">加载中...</td></tr>
          <tr v-for="(item, idx) in list" :key="idx">
            <td class="link">{{ item.demandNo }}</td>
            <td><span :class="statusClass(item.purchaseStatus)">{{ statusText(item.purchaseStatus) }}</span></td>
            <td>{{ item.productionWorkOrder || '-' }}</td>
            <td>
              <span class="link">{{ item.productName || '-' }}</span>
              <span class="sub">{{ item.productCode || '' }}</span>
            </td>
            <td>
              <span class="link">{{ item.materialName || '-' }}</span>
              <span class="sub">{{ item.materialCode || '' }}</span>
            </td>
            <td>{{ categoryText(item.category) }}</td>
            <td>{{ item.specification || item.spec || '-' }}</td>
            <td>{{ item.unitName || '-' }}</td>
            <td>{{ item.availableStock ?? '-' }}</td>
            <td>{{ item.requiredQuantity ?? '-' }}</td>
            <td>{{ item.netDemand ?? '-' }}</td>
            <td>{{ item.toBePurchased ?? '-' }}</td>
            <td>{{ item.purchasedAndStored ?? '-' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="footer-section">
      <div class="pagination">
        <button @click="onPageChange(pageNum-1)" :disabled="pageNum===1">&lt;</button>
        <button v-for="p in totalPages" :key="p" :class="{active: p===pageNum}" @click="onPageChange(p)">{{ p }}</button>
        <button @click="onPageChange(pageNum+1)" :disabled="pageNum===totalPages">&gt;</button>
        <el-select v-model.number="pageSize" style="width:120px" @change="onPageSizeChange">
          <el-option :value="5" label="5条/页" />
          <el-option :value="10" label="10条/页" />
          <el-option :value="20" label="20条/页" />
        </el-select>
      </div>
    </div>
  </div>

  <!-- 新建弹窗（占位） -->
  <el-dialog v-model="addOpen" title="新增采购需求" width="600px">
    <div>这里放新增表单内容</div>
    <template #footer>
      <el-button type="primary" @click="submitAdd">确 定</el-button>
      <el-button @click="addOpen=false">取 消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { listPurchaseDemand, addPurchaseDemand } from '@/api/purchase/demand'
export default {
  name: 'PurchaseDemand',
  data(){
    return {
      query: {
        keyword: '',
        purchaseStatus: ''
      },
      loading: false,
      list: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      addOpen: false
    }
  },
  computed:{
    totalPages(){
      return Math.max(1, Math.ceil((this.total||0)/(this.pageSize||10)))
    }
  },
  created(){
    this.fetchList()
  },
  methods:{
    async fetchList(){
      this.loading = true
      try{
        const kw = (this.query.keyword||'').trim() || undefined
        const params = {
          demandNo: kw,
          productionWorkOrder: kw,
          productName: kw,
          materialName: kw,
          purchaseStatus: this.query.purchaseStatus === '' ? undefined : this.query.purchaseStatus,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
        const res = await listPurchaseDemand(params)
        const payload = res?.data || res
        const ok = payload?.code === 200 || payload?.success === true
        const page = ok ? (payload.data || payload.page || payload.result || payload) : {}
        this.list = page.records || []
        this.total = page.total || 0
      } finally {
        this.loading = false
      }
    },
    onSearch(){ this.pageNum = 1; this.fetchList() },
    onReset(){ this.query = { keyword:'', purchaseStatus:'' }; this.pageNum = 1; this.fetchList() },
    openAdd(){ this.addOpen = true },
    async submitAdd(){ this.addOpen = false; /* 这里可调用 addPurchaseDemand */ },
    onPageChange(p){ const n = Math.min(Math.max(1,p), this.totalPages); if(n===this.pageNum) return; this.pageNum=n; this.fetchList() },
    onPageSizeChange(){ this.pageNum=1; this.fetchList() },
    statusText(v){ const m={0:'待采购入库',1:'部分采购入库',2:'全部采购入库'}; return m[Number(v)]||'-' },
    statusClass(v){ const m={0:'status-pending',1:'status-partial',2:'status-full'}; return m[Number(v)]||'status-default' },
    categoryText(v){ const m={0:'成品',1:'半成品',2:'原材料'}; return m[Number(v)]||'-' }
  }
}
</script>

<style scoped>
.purchase-demand-container{ padding:20px; background:#f5f7fa; }
.topbar{ display:flex; justify-content:space-between; align-items:center; background:#fff; padding:16px; border-radius:8px; }
.left{ display:flex; align-items:center; gap:12px; }
.right{ display:flex; align-items:center; gap:12px; }
.label{ color:#606266; }
.kw-input{ width: 260px; }
.status-select{ width: 120px; }
.table-section{ background:#fff; margin-top:16px; padding:16px; border-radius:8px; }
table{ width:100%; border-collapse:collapse; }
th,td{ padding:10px; border-bottom:1px solid #ebeef5; text-align:left; }
.link{ color:#409eff; }
.sub{ color:#909399; font-size:12px; margin-left:6px; }
.footer-section{ display:flex; justify-content:flex-end; align-items:center; margin-top:12px }
.pagination{ display:flex; align-items:center; gap:8px }
.pagination button{ padding:6px 10px; border:1px solid #dcdfe6; background:#fff; cursor:pointer; border-radius:4px }
.pagination button.active{ background:#409eff; color:#fff; border-color:#409eff }
</style>

<template>
  <div class="purchase-demand-container">
    <div class="filter-section">
      <div class="filter-item">
        <label>需求单号</label>
        <input v-model="query.demandNo" placeholder="请输入需求单号" />
      </div>
      <div class="filter-item">
        <label>工单</label>
        <input v-model="query.productionWorkOrder" placeholder="生产工单" />
      </div>
      <div class="filter-item">
        <label>产品</label>
        <input v-model="query.productName" placeholder="产品名称" />
      </div>
      <div class="filter-item">
        <label>物料</label>
        <input v-model="query.materialName" placeholder="物料名称" />
      </div>
      <div class="filter-item">
        <label>状态</label>
        <select v-model.number="query.purchaseStatus">
          <option :value="''">全部</option>
          <option :value="0">待采购入库</option>
          <option :value="1">部分采购入库</option>
          <option :value="2">全部采购入库</option>
        </select>
      </div>
      <div class="filter-buttons">
        <button class="btn-primary" @click="onSearch">搜索</button>
        <button class="btn-secondary" @click="onReset">重置</button>
        <el-button type="primary" @click="openAdd">新建</el-button>
      </div>
    </div>

    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th>采购需求单号</th>
            <th>采购状态</th>
            <th>生产计划</th>
            <th>生产产品</th>
            <th>所需物料</th>
            <th>分类</th>
            <th>规格</th>
            <th>单位</th>
            <th>可用库存</th>
            <th>所需用量</th>
            <th>净需求</th>
            <th>待采购数量</th>
            <th>已采购入库数量</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="13" style="text-align:center;padding:20px;">加载中...</td>
          </tr>
          <tr v-for="(item,idx) in list" :key="idx">
            <td class="link">{{ item.demandNo }}</td>
            <td><span :class="statusClass(item.purchaseStatus)">{{ statusText(item.purchaseStatus) }}</span></td>
            <td>{{ item.productionWorkOrder || '-' }}</td>
            <td>
              <span class="link">{{ item.productName || '-' }}</span>
              <span class="sub">{{ item.productCode || '' }}</span>
            </td>
            <td>
              <span class="link">{{ item.materialName || '-' }}</span>
              <span class="sub">{{ item.materialCode || '' }}</span>
            </td>
            <td>{{ categoryText(item.category) }}</td>
            <td>{{ item.specification || item.spec || '-' }}</td>
            <td>{{ item.unitName || '-' }}</td>
            <td>{{ item.availableStock ?? '-' }}</td>
            <td>{{ item.requiredQuantity ?? '-' }}</td>
            <td>{{ item.netDemand ?? '-' }}</td>
            <td>{{ item.toBePurchased ?? '-' }}</td>
            <td>{{ item.purchasedAndStored ?? '-' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="footer-section">
      <div class="pagination">
        <button @click="onPageChange(query.pageNum-1)" :disabled="query.pageNum===1">&lt;</button>
        <button v-for="p in totalPages" :key="p" :class="{active: p===query.pageNum}" @click="onPageChange(p)">{{ p }}</button>
        <button @click="onPageChange(query.pageNum+1)" :disabled="query.pageNum===totalPages">&gt;</button>
        <select v-model.number="query.pageSize" @change="onPageSizeChange">
          <option :value="5">5条/页</option>
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>
        </select>
      </div>
    </div>
    <!-- 新增弹窗 -->
    <el-dialog v-model="addOpen" title="新增采购需求" width="640px">
      <div class="form-grid">
        <el-form :model="addForm" label-width="120px">
          <el-form-item label="生产工单">
            <el-input v-model="addForm.productionWorkOrder" placeholder="SCGD..." />
          </el-form-item>
          <el-form-item label="产品名称">
            <el-input v-model="addForm.productName" />
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input v-model="addForm.materialName" />
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model.number="addForm.category" style="width:100%">
              <el-option :value="0" label="成品" />
              <el-option :value="1" label="半成品" />
              <el-option :value="2" label="原材料" />
            </el-select>
          </el-form-item>
          <el-form-item label="采购状态">
            <el-select v-model.number="addForm.purchaseStatus" style="width:100%">
              <el-option :value="0" label="待采购入库" />
              <el-option :value="1" label="部分采购入库" />
              <el-option :value="2" label="全部采购入库" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="addForm.remark" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" @click="submitAdd">确 定</el-button>
        <el-button @click="addOpen=false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchaseDemand } from '@/api/purchase/demand'

export default {
  name: 'PurchaseDemand',
  data(){
    return {
      loading: false,
      list: [],
      total: 0,
      query: {
        pageNum: 1,
        pageSize: 10,
        demandNo: '',
        purchaseStatus: '',
        productionWorkOrder: '',
        productName: '',
        materialName: ''
      },
      addOpen: false,
      addForm: {
        demandNo: '',
        productionWorkOrder: '',
        productName: '',
        materialName: '',
        category: 0,
        purchaseStatus: 0,
        remark: ''
      }
    }
  },
  computed:{
    totalPages(){
      return Math.max(1, Math.ceil((this.total||0)/(this.query.pageSize||10)))
    }
  },
  created(){
    this.fetchList()
  },
  methods:{
    async fetchList(){
      this.loading = true
      try{
        const params = {
          demandNo: this.query.demandNo || undefined,
          purchaseStatus: this.query.purchaseStatus === '' ? undefined : this.query.purchaseStatus,
          productionWorkOrder: this.query.productionWorkOrder || undefined,
          productName: this.query.productName || undefined,
          materialName: this.query.materialName || undefined,
          pageNum: this.query.pageNum,
          pageSize: this.query.pageSize
        }
        const res = await listPurchaseDemand(params)
        const payload = res?.data || res
        const ok = payload?.code === 200 || payload?.success === true
        const page = ok ? (payload.data || payload.page || payload.result || payload) : {}
        this.list = page.records || []
        this.total = page.total || 0
      } finally {
        this.loading = false
      }
    },
    onSearch(){
      this.query.pageNum = 1
      this.fetchList()
    },
    onReset(){
      this.query = { pageNum:1, pageSize:10, demandNo:'', purchaseStatus:'', productionWorkOrder:'', productName:'', materialName:'' }
      this.fetchList()
    },
    onPageChange(p){
      const n = Math.min(Math.max(1,p), this.totalPages)
      if(n===this.query.pageNum) return
      this.query.pageNum = n
      this.fetchList()
    },
    onPageSizeChange(){
      this.query.pageNum = 1
      this.fetchList()
    },
    statusText(v){
      const m={0:'待采购入库',1:'部分采购入库',2:'全部采购入库'}
      return m[Number(v)] || '-'
    },
    statusClass(v){
      const m={0:'status-pending',1:'status-partial',2:'status-full'}
      return m[Number(v)] || 'status-default'
    },
    categoryText(v){
      const m={0:'成品',1:'半成品',2:'原材料'}
      return m[Number(v)] || '-'
    },
    openAdd(){
      this.addForm = { demandNo:'', productionWorkOrder:'', productName:'', materialName:'', category:0, purchaseStatus:0, remark:'' }
      this.addOpen = true
    },
    async submitAdd(){
      const payload = { ...this.addForm }
      const { addPurchaseDemand } = await import('@/api/purchase/demand')
      const res = await addPurchaseDemand(payload)
      const ok = res?.data?.code === 200 || res?.code === 200 || res?.data?.success === true
      if(ok){
        this.$message?.success?.('新增成功')
        this.addOpen = false
        this.fetchList()
      }else{
        this.$message?.error?.(res?.data?.message || res?.data?.msg || '新增失败')
      }
    }
  }
}
</script>

<style scoped>
.purchase-demand-container{padding:20px;background:#f5f7fa}
.filter-section{display:flex;gap:16px;padding:16px;background:#fff;border-radius:8px;margin-bottom:16px;align-items:center}
.filter-item{display:flex;align-items:center;gap:8px}
.filter-buttons{margin-left:auto}
.btn-primary{background:#409eff;color:#fff;border:none;padding:8px 16px;border-radius:4px;cursor:pointer}
.btn-secondary{background:#fff;color:#606266;border:1px solid #dcdfe6;padding:8px 16px;border-radius:4px;cursor:pointer}
.table-section{background:#fff;padding:16px;border-radius:8px}
table{width:100%;border-collapse:collapse}
th,td{padding:10px;border-bottom:1px solid #ebeef5;text-align:left}
.link{color:#409eff}
.sub{color:#909399;font-size:12px;margin-left:6px}
.footer-section{display:flex;justify-content:flex-end;align-items:center;margin-top:12px}
.pagination{display:flex;align-items:center;gap:8px}
.pagination button{padding:6px 10px;border:1px solid #dcdfe6;background:#fff;cursor:pointer;border-radius:4px}
.pagination button.active{background:#409eff;color:#fff;border-color:#409eff}
.status-pending{color:#909399}
.status-partial{color:#e6a23c}
.status-full{color:#67c23a}
.status-default{color:#606266}
</style>

